import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author sk.z
 * 集合交集时合并
 */
public class MergeInJoin {

    public static void main(String[] args) {
        List<Set<String>> setList = new ArrayList<>();
        setList.add(buildSet("A","B"));
        setList.add(buildSet("C","D"));
        setList.add(buildSet("E","F"));
        setList.add(buildSet("G","H"));
        setList.add(buildSet("B","F"));
        setList.add(buildSet("E","I"));
        setList.add(buildSet("J","K"));
        setList.add(buildSet("J","L"));

        show(setList);
        while (merge(setList)){
            show(setList);
        }
        show(setList);
    }

    //合并
    public static boolean merge(List<Set<String>> setList){
        for (int i=0; i<setList.size(); i++){
            Set<String> curSet = setList.get(i);
            for (int n=i+1; n<setList.size();n++){
                Set<String> nextSet = setList.get(n);
                //是否存在交际
                if (isInJoin(curSet,nextSet)){
                    curSet.addAll(nextSet);
                    setList.remove(n);
                    return true;
                }
            }
        }
        return false;
    }

    //set是否存在交际
    private static boolean isInJoin(Set<String> left, Set<String> right){
        for (String l : left){
            if (right.contains(l)){
                return true;
            }
        }
        return false;
    }

    private static Set<String> buildSet(String a, String b){
        Set<String> set = new HashSet<>();
        set.add(a);
        set.add(b);
        return set;
    }

    private static void show(List<Set<String>> setList){
        for (Set<String> set : setList){
            System.out.println(set);
        }
        System.out.println();
    }
}
